package jh.com.jhappbf.contract;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.PriceModel;
import jh.com.jhappbf.model.PriceSettingModel;
import jh.com.jhappbf.utils.JsonHelper;

public class PriceQuery extends AbActivity {
    private View mContentView;
    private View mErrorView;
    private List<JSONObject> mData;
    private AbTitleBar mTitleBar;
    private AbPullToRefreshView mRefreshView; // 下拉刷新上拉加载更多
    private AbLoadDialogFragment mDialogFragment = null;
    private ListView mListView;
    private LinearLayout mTitleLayout;
    private Button mTryAgain;
    private int mCurrentPage = 0;
    private List<String> mHeaderContent;
    private Context mAppcontext;
    private MyBaseAdapter mAdapter;
    private int mCurrentScreenWidth;
    private PriceSettingModel mSettingModel;
    private Drawable mLeftDrawable;
    private final int mPageSize = 30;
    private final int UPDATEPRICE = 0X0001;
    private final int ADDPRICE = 0X0002;
    private final int GETSETTING = 0X0003;
    private List<JSONObject> mTemp;
    private Button mRightBtn;
    private String mStates = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContentView = View.inflate(this, R.layout.list_view_universal_activity, null);
        mErrorView = View.inflate(this, R.layout.net_error_activity, null);
        mAppcontext = getApplicationContext();
        setAbContentView(mContentView);
        Intent i = getIntent();
        mSettingModel = i.getParcelableExtra("setting");
        mTitleBar = getTitleBar();
        mTitleBar.setTitleText("单价管理");
        mTitleBar.setLogo(R.drawable.button_selector_back);
        mTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mTitleBar.setLogoLine(R.mipmap.line);
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        mRefreshView = mContentView.findViewById(R.id.universal_pullToRefreshView);
        mListView = mContentView.findViewById(R.id.universal_listView);
        mTitleLayout = mContentView.findViewById(R.id.universal_title);
        mTryAgain = mErrorView.findViewById(R.id.network_error_btn);

        View v = getLayoutInflater().inflate(R.layout.title_right_app_btn_view, null);
        mTitleBar.addRightView(v);
        mRightBtn = v.findViewById(R.id.title_right_btn);
        mRightBtn.setOnClickListener(v1 -> {
            Intent i = new Intent(PriceQuery.this, PriceSelectSetting.class);
            i.putExtra("setting", mSettingModel);
            startActivityForResult(i, GETSETTING);
        });

        mCurrentScreenWidth = getWidth(4);
        mLeftDrawable = ContextCompat.getDrawable(this, R.mipmap.table_line);
        mLeftDrawable.setBounds(0, 0, mLeftDrawable.getMinimumWidth(),
                mLeftDrawable.getMinimumHeight());
        mData = new ArrayList<>();
        mTemp = new ArrayList<>();
        mHeaderContent = new ArrayList<>();
        mHeaderContent.add("序号");
        mHeaderContent.add("货名");
        mHeaderContent.add("收货");
        mHeaderContent.add("发货");
        mHeaderContent.add("类型");
        mHeaderContent.add("单价");
        mAdapter = new MyBaseAdapter();
        mListView.setAdapter(mAdapter);

        mListView.setOnItemLongClickListener((parent, view, position, id) -> {
            PopupMenu menu = new PopupMenu(PriceQuery.this, view);

            if ("0".equals(mStates)) {
                getMenuInflater().inflate(R.menu.price_manager,
                        menu.getMenu());
            } else {
                getMenuInflater().inflate(R.menu.price_start_menu,
                        menu.getMenu());
            }

            menu.setOnMenuItemClickListener(item -> {
                switch (item.getItemId()) {
                    case R.id.price_update_menu_item:
                        updatePrice(position);
                        break;
                    case R.id.price_delete_menu_item:
                        deletePrice(position);
                        break;
                    case R.id.price_stop_menu_item:
                        stopOrStartPrice(position, "1");
                        break;
                    case R.id.price_start_menu_item:
                        stopOrStartPrice(position, "0");
                        break;
                    default:
                        break;
                }
                return true;
            });
            menu.show();
            return true;
        });


        mRefreshView.setOnHeaderRefreshListener(arg0 -> LoadFirst());

        mRefreshView.setOnFooterLoadListener(arg0 -> loadMoreTask());
        LoadFirst();
    }

    /**
     * 更新单价
     *
     * @param position
     */
    private void updatePrice(int position) {
        PriceModel priceModel = new PriceModel();
        JSONObject obj = mData.get(position);
        priceModel.setId(obj.optString("单价编号"));
        priceModel.setPlanId(obj.optString("合同编号"));
        priceModel.setCargoname(obj.optString("货名"));
        priceModel.setPrice(obj.optString("单价"));
        priceModel.setType(obj.optString("类型"));
        priceModel.setSender(obj.optString("发货"));
        priceModel.setReceiver(obj.optString("收货"));

        Intent i = new Intent(PriceQuery.this, PriceUpdate.class);
        i.putExtra("data", priceModel);
        startActivityForResult(i, UPDATEPRICE);
    }

    /**
     * 删除单价
     *
     * @param position
     */
    private void deletePrice(final int position) {
        String methodName = "delPrice";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        String id = mData.get(position).optString("单价编号");
        param.add("id");
        value.add(id);

        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(PriceQuery.this);
            List<JSONObject> newListData = JsonHelper.getJsonObjects(response);
            if (newListData != null && newListData.size() > 0) {
                JSONObject obj = newListData.get(0);
                String value1 = obj.optString("result");
                String memo = obj.optString("memo");
                if ("true".equals(value1)) {
                    PriceQuery.this.setResult(RESULT_OK);
                    Toast.makeText(PriceQuery.this, memo,
                            Toast.LENGTH_SHORT).show();
                    mData.remove(position);
                    mAdapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(PriceQuery.this, memo,
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(PriceQuery.this, "操作失败,请重试",
                        Toast.LENGTH_SHORT).show();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(PriceQuery.this);
            Toast.makeText(PriceQuery.this, "操作失败,请重试",
                    Toast.LENGTH_SHORT).show();
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppcontext).addRequest(webService);
    }

    /**
     * 停用单价
     *
     * @param position
     */
    private void stopOrStartPrice(final int position, String flag) {
        String methodName = "setPricesState";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        String id = mData.get(position).optString("单价编号");
        param.add("id");
        param.add("state");

        value.add(id);
        value.add(flag);

        Listener<String> listener = response -> {
            AbDialogUtil.removeDialog(PriceQuery.this);
            List<JSONObject> newListData = JsonHelper
                    .getJsonObjects(response);
            if (newListData != null && newListData.size() > 0) {
                JSONObject obj = newListData.get(0);
                String value1 = obj.optString("result");
                String memo = obj.optString("memo");
                if ("true".equals(value1)) {
                    PriceQuery.this.setResult(RESULT_OK);
                    Toast.makeText(PriceQuery.this, memo,
                            Toast.LENGTH_SHORT).show();
                    mData.remove(position);
                    mAdapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(PriceQuery.this, memo,
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(PriceQuery.this, "操作失败,请重试",
                        Toast.LENGTH_SHORT).show();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(PriceQuery.this);
            Toast.makeText(PriceQuery.this, "操作失败,请重试",
                    Toast.LENGTH_SHORT).show();
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppcontext).addRequest(webService);
    }


    /**
     * 第一次加载
     */
    private void LoadFirst() {
        mDialogFragment = AbDialogUtil.showLoadDialog(PriceQuery.this,
                R.mipmap.ic_load, "加载中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(() -> {
            mContentView.setVisibility(View.VISIBLE);
            refreshTask();
        });
    }


    /**
     * 制作表头
     */
    private void makeHeader() {
        mTitleLayout.removeAllViews();
        TableLayout table = new TableLayout(mAppcontext);
        TableRow row = new TableRow(mAppcontext);
        for (int index = 0; index < mHeaderContent.size(); index++) {
            TextView txt = new TextView(PriceQuery.this);
            switch (mHeaderContent.get(index)) {
                case "单价编号":
                case "合同编号":
                case "货名":
                    txt.setWidth((int) (mCurrentScreenWidth * 2.5));
                    break;
                case "时间":
                    txt.setWidth(mCurrentScreenWidth * 3);
                    break;
                case "收货":
                    txt.setWidth((int) (mCurrentScreenWidth * 2.5));
                    break;
                case "剩余吨数":
                case "发货":
                    txt.setWidth((int) (mCurrentScreenWidth * 1.5));
                    break;
                default:
                    txt.setWidth(mCurrentScreenWidth);
                    break;
            }
            txt.setTextColor(Color.BLACK);
            txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            txt.setGravity(Gravity.CENTER);
            txt.setPadding(1, 0, 1, 0);
            txt.setId(index);
            txt.setText(mHeaderContent.get(index));
            txt.setCompoundDrawables(mLeftDrawable, null, null, null);
            row.addView(txt);
        }
        table.addView(row);
        mTitleLayout.addView(table);
    }

    /**
     * 根据列数获取列宽
     *
     * @param columnCount 列的个数
     * @return 平均列宽
     */
    private int getWidth(int columnCount) {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        return (metrics.widthPixels) / (columnCount * 2);
    }

    /**
     * 下拉刷新
     */
    private void refreshTask() {

        String methodName = "queryAllPrice";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("currentPageStr");
        param.add("pageSizeStr");
        param.add("startTime");
        param.add("endTime");
        param.add("spec");
        param.add("cargoname");
        param.add("sender");
        param.add("receiver");
        param.add("states");

        value.add("1");
        value.add(String.valueOf(mPageSize));
        if (mSettingModel == null) {
            Date date = new Date();
            String end = "";
            String start = "";
            value.add(start);
            value.add(end);
            value.add("");
            value.add("");
            value.add("");
            value.add("");
            value.add("0");

        } else {
            value.add(mSettingModel.getStartTime());
            value.add(mSettingModel.getEndTime());
            value.add(mSettingModel.getSpec());
            value.add(mSettingModel.getCargoname());
            value.add(mSettingModel.getSender());
            value.add(mSettingModel.getReceiver());
            mStates = mSettingModel.getStates();
            value.add(mStates);
        }


        Listener<String> listener = response -> {

            AbDialogUtil.removeDialog(PriceQuery.this);
            mRefreshView.onHeaderRefreshFinish();
            List<JSONObject> newListData = JsonHelper
                    .getJsonObjects(response);
            if (newListData != null) {
                mData.clear();
                mData.addAll(newListData);
                if (newListData.size() == mPageSize) {
                    mCurrentPage++;
                }
                if (newListData.size() > 0) {
                    getHeaderTitle(newListData.get(0));
                }
                mAdapter.notifyDataSetChanged();
            }
        };

        ErrorListener errorListener = error -> {
            AbDialogUtil.removeDialog(PriceQuery.this);
            mRefreshView.onHeaderRefreshFinish();
            setAbContentView(mErrorView);
            mAdapter.notifyDataSetChanged();
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppcontext).addRequest(webService);
    }

    /**
     * 获取文件头
     *
     * @param obj
     */
    private void getHeaderTitle(JSONObject obj) {
        String[] alias = obj.optString("alias").split(",");
        if (alias.length > 0) {
            mHeaderContent.clear();
            for (String item : alias) {
                if (!"序号".equals(item)) {
                    mHeaderContent.add(item);
                }
            }
        }
        makeHeader();
    }

    /**
     * 上拉加载更多
     */
    private void loadMoreTask() {
        String methodName = "queryAllPrice";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("currentPageStr");
        param.add("pageSizeStr");
        param.add("startTime");
        param.add("endTime");
        param.add("spec");
        param.add("cargoname");
        param.add("sender");
        param.add("receiver");
        param.add("states");

        value.add(String.valueOf(mCurrentPage));
        value.add(String.valueOf(mPageSize));
        if (mSettingModel == null) {
            Date date = new Date();
            String end = "";
            String start = "";
            value.add(start);
            value.add(end);
            value.add("");
            value.add("");
            value.add("");
            value.add("");
            value.add("0");

        } else {
            value.add(mSettingModel.getStartTime());
            value.add(mSettingModel.getEndTime());
            value.add(mSettingModel.getSpec());
            value.add(mSettingModel.getCargoname());
            value.add(mSettingModel.getSender());
            value.add(mSettingModel.getReceiver());
            mStates = mSettingModel.getStates();
            value.add(mStates);
        }

        Listener<String> listener = response -> {
            mRefreshView.onFooterLoadFinish();
            if (mTemp != null && mTemp.size() < mPageSize) {
                mData.removeAll(mTemp);
                mTemp.clear();
            }
            mTemp = JsonHelper.getJsonObjects(response);
            if (mTemp != null && mTemp.size() > 0) {
                mData.addAll(mTemp);
                mAdapter.notifyDataSetChanged();
                if (mTemp.size() == mPageSize) {
                    mCurrentPage++;
                }
            }
        };

        ErrorListener errorListener = error -> {
            mRefreshView.onFooterLoadFinish();
            setAbContentView(mErrorView);
            AbToastUtil.showToast(mAppcontext, "数据加载失败！");
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppcontext).addRequest(webService);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == UPDATEPRICE && resultCode == RESULT_OK) {
            LoadFirst();
        } else if (requestCode == ADDPRICE && resultCode == RESULT_OK) {
            LoadFirst();
        } else if (data != null && requestCode == GETSETTING) {
            mSettingModel = data.getParcelableExtra("result");
            LoadFirst();
        }
    }

    class MyBaseAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint("NewApi")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            TableLayout tableLayout;

            if (convertView == null) {
                tableLayout = new TableLayout(PriceQuery.this);
                TableRow tableRow = new TableRow(PriceQuery.this);
                Drawable mItemSelect = ContextCompat.getDrawable(PriceQuery.this, R.drawable.list_item_bg);
                tableRow.setBackground(mItemSelect);
                tableRow.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);

                for (int index = 0; index < mHeaderContent.size(); index++) {
                    TextView txt = new TextView(PriceQuery.this);
                    switch (mHeaderContent.get(index)) {
                        case "单价编号":
                        case "合同编号":
                        case "货名":
                            txt.setWidth((int) (mCurrentScreenWidth * 2.5));
                            break;
                        case "时间":
                            txt.setWidth(mCurrentScreenWidth * 3);
                            break;
                        case "收货":
                            txt.setWidth((int) (mCurrentScreenWidth * 2.5));
                            break;
                        case "剩余吨数":
                        case "发货":
                            txt.setWidth((int) (mCurrentScreenWidth * 1.5));
                            break;
                        default:
                            txt.setWidth(mCurrentScreenWidth);
                            break;
                    }

                    txt.setTextColor(Color.BLACK);
                    txt.setGravity(Gravity.CENTER);
                    txt.setCompoundDrawables(mLeftDrawable, null, null, null);
                    txt.setPadding(1, 10, 1, 10);
                    txt.setId(index);
                    txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                    tableRow.addView(txt);
                }
                tableLayout.addView(tableRow);
                convertView = tableLayout;
                convertView.setTag(tableLayout);
            } else {
                tableLayout = (TableLayout) convertView.getTag();
            }

            JSONObject data = mData.get(position);
            String content;
            for (int index = 0; index < mHeaderContent.size(); index++) {
                View view = tableLayout.getChildAt(0).findViewById(index);
                if (view instanceof TextView) {
                    TextView txt = (TextView) view;
                    content = data.optString(mHeaderContent.get(index));
                    if ("null".equals(content)) {
                        content = "";
                    }
                    txt.setText(content);
                }
            }

            return convertView;
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }
}